import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { RoleService } from '../role/role.service';
import { UsersService } from '../users/users.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly roleService: RoleService,
    private readonly userService: UsersService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'tuotuo',
    });
  }

  async validate(payload: any) {
    const qd = await this.userService.findOne(payload.name);
    return {
      userId: payload.sub,
      username: payload.name,
      type: payload.type,
      role: qd.role,
      authority: qd.role?.authority ?? [],
    };
  }
}
